package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.DateRanger;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.SysDictDataCacheDTO;
import com.ruoyi.system.domain.dto.SysDictTypeInput;
import com.ruoyi.system.domain.dto.SysDictTypeUpdateInput;
import com.ruoyi.system.filter.AuthDataFilter;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author ruoyi
 */
@Service
@RequiredArgsConstructor
public class SysDictTypeServiceImpl implements ISysDictTypeService {

    private final JSqlClient sqlClient;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param input 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictTypeInput input, DateRanger dateRanger) {
        SysDictTypeTable table = SysDictTypeTable.$;
        return sqlClient.createQuery(table)
                .whereIf(input.getStatus() != null && !input.getStatus().isEmpty(), () -> table.status().eq(input.getStatus()))
                .whereIf(StringUtils.isNotEmpty(input.getDictName()), () -> table.dictName().ilike(input.getDictName()))
                .whereIf(StringUtils.isNotEmpty(input.getDictType()), () -> table.dictType().ilike(input.getDictType()))
                .whereIf(DateRanger.isAllNotEmpty(dateRanger), () -> table.createTime().between(dateRanger.getBeginTime(), dateRanger.getEndTime()))
                .select(
                        table.fetch(SysDictTypeFetcher.$.allScalarFields())
                ).execute();
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        SysDictTypeTable table = SysDictTypeTable.$;
        return sqlClient.createQuery(table)
                .select(table.fetch(SysDictTypeFetcher.$.allScalarFields()))
                .execute();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictDataCacheDTO> selectDictDataByType(String dictType) {
        List<SysDictDataCacheDTO> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return sqlClient.findById(SysDictTypeFetcher.$.allScalarFields(), dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    /*@Override
    public SysDictType selectDictTypeByType(String dictType) {
        return dictTypeMapper.selectDictTypeByType(dictType);
    }*/

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        SysDictDataTable table = SysDictDataTable.$;
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);

            long count = sqlClient.createQuery(table).where(table.dictType().eq(dictType.dictType())).selectCount().fetchOne();
            if (count > 0L) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.dictName()));
            }
            sqlClient.deleteById(SysDictType.class, dictId);
            DictUtils.removeDictCache(dictType.dictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        SysDictDataTable table = SysDictDataTable.$;
        Map<String, List<SysDictDataCacheDTO>> dictDataMap = sqlClient.filters(it-> it.disableByTypes(AuthDataFilter.class))
                .createQuery(table)
                .where(table.status().eq("0"))
                .select(table.fetch(
                        SysDictDataFetcher.$.allScalarFields()
                ))
                .execute().stream().map(SysDictDataCacheDTO::new).collect(Collectors.groupingBy(SysDictDataCacheDTO::getDictType));

        for (Map.Entry<String, List<SysDictDataCacheDTO>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictDataCacheDTO::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictTypeUpdateInput dict) {
        SysDictType dictType = SysDictTypeDraft.$
                .produce(dict.toEntity(), draft -> draft.applyCreateBy(user -> user.setUserId(SecurityUtils.getUserId())));
        int row = sqlClient.saveCommand(dictType)
                .setMode(SaveMode.INSERT_ONLY)
                .execute()
                .getTotalAffectedRowCount();
        if (row > 0) {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictTypeUpdateInput dict) {
        SysDictType oldDict = sqlClient.findById(SysDictTypeFetcher.$.allScalarFields(), dict.getDictId());
        SysDictDataTable dataTable = SysDictDataTable.$;
        sqlClient.createUpdate(dataTable)
                .set(dataTable.dictType(), dict.getDictType())
                .where(dataTable.dictType().eqIf(oldDict.dictType()))
                .execute();
        SysDictType dictType = SysDictTypeDraft.$
                .produce(dict.toEntity(), draft -> draft.applyUpdateBy(user -> user.setUserId(SecurityUtils.getUserId())));
        int row = sqlClient.saveCommand(dictType)
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
        if (row > 0) {
            List<SysDictDataCacheDTO> dictDatas = sqlClient.createQuery(dataTable)
                    .where(dataTable.dictType().eq(dict.getDictType()))
                    .select(dataTable.fetch(SysDictDataCacheDTO.class)).execute();
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictTypeUpdateInput dict) {
        long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictTypeTable table = SysDictTypeTable.$;
        SysDictType dictType = sqlClient.createQuery(table)
                .where(table.dictType().eq(dict.getDictType()))
                .select(
                        table.fetch(SysDictTypeFetcher.$.allScalarFields())
                ).fetchOneOrNull();
        if (StringUtils.isNotNull(dictType) && dictType.dictId() != dictId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
